package com.msg.core.handle;

import cn.hutool.core.util.StrUtil;
import com.msg.core.exception.ProjectException;
import com.msg.core.result.RespEnum;
import com.msg.core.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;


/**
 * 全局异常处理器
 *
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	/**
	 * springboot的各组件执行顺序
	 *
	 * 入方向--------->
	 *      过滤器----拦截器----controller advice----aop----controller
	 * 出方向<--------
	 */


	/**
	 * 请求方式不支持
	 */
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public Result<?> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
			HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址[{}],不支持[{}]请求", requestURI, e.getMethod());
		return Result.error(e.getMessage());
	}

	/**
	 * 拦截未知的运行时异常
	 */
	@ExceptionHandler(RuntimeException.class)
	public Result<?> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址[{}],发生未知异常.", requestURI, e);
		return Result.error(e.getMessage());
	}

	/**
	 * 系统异常
	 */
	@ExceptionHandler(Exception.class)
	public Result<?> handleException(Exception e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址[{}],发生系统异常.", requestURI, e);
		return Result.error(e.getMessage());
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		log.error(e.getMessage(), e);
		String message = e.getBindingResult().getFieldError().getDefaultMessage();
		return Result.error(message);
	}


	/**
	 * desc 处理业务异常
	 *
	 * @param req
	 * @return
	 */
	@ExceptionHandler(ProjectException.class)
	public Result<?> projectException(ProjectException pe, HttpServletRequest req) {
		log.info("业务异常,请求地址:[{}],错误信息：{}", req.getRequestURL(), getErrMsg(pe),pe);
		return Result.error(pe.getProExp(),pe.getErrMsg());
	}

	/**
	 * 获取错误信息
	 */
	private String getErrMsg(ProjectException pe){
		RespEnum proExp=pe.getProExp();
		return StrUtil.isNotBlank(pe.getErrMsg())?pe.getErrMsg():proExp!=null?proExp.getMsg():"";
	}
}
